'use client';

import { useState, useRef, useEffect } from 'react';
import { RiSendPlaneFill } from '@remixicon/react';
import ChatMessage from './chat-message';
import ChatSessionList from './chat-session-list';

interface Message {
  id: string;
  role: 'user' | 'assistant' | 'system';
  content: string;
  timestamp: number;
  status?: 'thinking' | 'error' | 'done';
  type?: 'text' | 'image' | 'video' | 'file';
}

interface ChatSession {
  id: string;
  title: string;
  lastMessage: string;
  timestamp: number;
  messageCount: number;
  messages: Message[];
}

interface ChatBoxProps {
  appKey: string;
}

export default function ChatBox({ appKey }: ChatBoxProps) {
  const [currentSession, setCurrentSession] = useState<ChatSession | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  // 加载当前会话的消息
  useEffect(() => {
    if (currentSession) {
      setMessages(currentSession.messages);
    } else {
      // 如果没有当前会话，显示欢迎消息
      const welcomeMessage: Message = {
        id: 'welcome',
        role: 'system',
        content: '欢迎使用AI助手，我可以帮助您解答问题。',
        timestamp: Date.now(),
        status: 'done',
        type: 'text'
      };
      setMessages([welcomeMessage]);
    }
  }, [currentSession]);

  // 自动滚动到底部
  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 自动调整输入框高度
  useEffect(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
      textareaRef.current.style.height = textareaRef.current.scrollHeight + 'px';
    }
  }, [inputValue]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  // 处理会话选择
  const handleSessionSelect = (sessionId: string) => {
    // TODO: 从本地存储或后端加载会话
    console.log('Selected session:', sessionId);
  };

  // 处理新建会话
  const handleNewSession = () => {
    const newSession: ChatSession = {
      id: Date.now().toString(),
      title: '新的对话',
      lastMessage: '',
      timestamp: Date.now(),
      messageCount: 0,
      messages: []
    };
    setCurrentSession(newSession);
    // TODO: 保存到本地存储或后端
  };

  // 处理删除会话
  const handleDeleteSession = (sessionId: string) => {
    if (currentSession?.id === sessionId) {
      setCurrentSession(null);
    }
    // TODO: 从本地存储或后端删除会话
  };

  // 处理重命名会话
  const handleRenameSession = (sessionId: string, newTitle: string) => {
    if (currentSession?.id === sessionId) {
      setCurrentSession(prev => prev ? { ...prev, title: newTitle } : null);
    }
    // TODO: 更新本地存储或后端
  };

  // 处理发送消息
  const handleSendMessage = async () => {
    if (!inputValue.trim() || isLoading) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      role: 'user',
      content: inputValue.trim(),
      timestamp: Date.now(),
      status: 'done',
      type: 'text'
    };

    // 添加思考状态消息
    const thinkingMessage: Message = {
      id: (Date.now() + 1).toString(),
      role: 'assistant',
      content: '思考中...',
      timestamp: Date.now(),
      status: 'thinking',
      type: 'text'
    };

    setMessages(prev => [...prev, userMessage, thinkingMessage]);
    setInputValue('');
    setIsLoading(true);

    try {
      // TODO: 这里添加实际的 AI 响应逻辑
      // 模拟 AI 响应
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 更新思考状态消息为实际响应
      const aiMessage: Message = {
        id: thinkingMessage.id,
        role: 'assistant',
        content: `这是来自 ${appKey} 的回复：${userMessage.content}`,
        timestamp: Date.now(),
        status: 'done',
        type: 'text'
      };

      const newMessages = messages.map(msg => 
        msg.id === thinkingMessage.id ? aiMessage : msg
      );
      setMessages(newMessages);

      // 更新当前会话
      if (currentSession) {
        const updatedSession = {
          ...currentSession,
          lastMessage: aiMessage.content,
          messageCount: newMessages.length,
          messages: newMessages,
          timestamp: Date.now()
        };
        setCurrentSession(updatedSession);
        // TODO: 保存到本地存储或后端
      }
    } catch (error) {
      // 更新思考状态消息为错误状态
      const errorMessage: Message = {
        id: thinkingMessage.id,
        role: 'system',
        content: '抱歉，处理您的请求时出现错误。',
        timestamp: Date.now(),
        status: 'error',
        type: 'text'
      };

      setMessages(prev => prev.map(msg => 
        msg.id === thinkingMessage.id ? errorMessage : msg
      ));
      console.error('Error getting AI response:', error);
    } finally {
      setIsLoading(false);
    }
  };

  // 处理按键事件
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  return (
    <div className="flex h-full bg-gray-50">
      {/* 会话列表侧边栏 */}
      <div className="w-64 border-r border-gray-200 bg-white">
        <ChatSessionList
          currentSessionId={currentSession?.id}
          onSessionSelect={handleSessionSelect}
          onNewSession={handleNewSession}
          onDeleteSession={handleDeleteSession}
          onRenameSession={handleRenameSession}
        />
      </div>

      {/* 主聊天区域 */}
      <div className="flex-1 flex flex-col">
        {/* 消息列表 */}
        <div className="flex-1 overflow-y-auto p-4">
          <div className="max-w-3xl mx-auto">
            {messages.map(message => (
              <ChatMessage
                key={message.id}
                role={message.role}
                content={message.content}
                status={message.status}
                type={message.type}
              />
            ))}
            <div ref={messagesEndRef} />
          </div>
        </div>

        {/* 输入区域 */}
        <div className="border-t border-gray-200 bg-white p-4">
          <div className="max-w-3xl mx-auto relative">
            <textarea
              ref={textareaRef}
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder="输入消息..."
              className="w-full pr-12 pl-4 py-3 resize-none rounded-lg border border-gray-200 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 outline-none min-h-[50px] max-h-[200px]"
              rows={1}
            />
            <button
              onClick={handleSendMessage}
              disabled={isLoading || !inputValue.trim()}
              className="absolute right-2 bottom-2 p-2 text-blue-500 hover:text-blue-600 disabled:text-gray-400"
            >
              <RiSendPlaneFill className="w-6 h-6" />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
} 